﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace JetBlack.Collections.Specialized
{
    internal class AsynchQueue<T> : IDisposable
    {
        public event Action<T> OnItemDequeued;

        private BlockingListQueue<T> queue = new BlockingListQueue<T>();
        private Thread thread = null;

        public AsynchQueue(bool startProcessing)
        {
            thread = new Thread(this.ProcessQueue);
            thread.Name = "AsynchQueue";
            if (startProcessing)
                StartProcessing();
        }

        public void StartProcessing()
        {
            if (thread.ThreadState == ThreadState.Unstarted)
                thread.Start();
        }

        private void ProcessQueue()
        {
            try
            {
                while (true)
                {
                    T item = queue.Dequeue();
                    if (!(OnItemDequeued == null || item == null))
                        OnItemDequeued(item);
                }
            }
            catch (QueueEmptyException)
            {
            }
        }

        public void Enqueue(T item)
        {
            queue.Enqueue(item);
        }

        public void Remove(T item)
        {
            if (queue.Contains(item))
                queue.Remove(item);
        }

        public void Close()
        {
            queue.Close();
        }

        public void Dispose()
        {
            if (!queue.IsClosing)
                queue.Close();
            thread.Join();
            queue.Dispose();
        }

        public int Count
        {
            get { return queue.Count; }
        }
    }
}
